package com.xiaolei.fastnio.library.Factorys.Impls

import com.xiaolei.fastnio.library.Adapters.IClientAdapter
import com.xiaolei.fastnio.library.Factorys.IClientAdapterFactory
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance

/**
 * 缓存所有会话的工厂类
 */
class CacheClientAdapterFactory<T : IClientAdapter>(private val klass: KClass<T>) : IClientAdapterFactory<T>
{
    /**
     * 主要保存 UUID与客户端Adapter的关系
     */
    private val cache = ConcurrentHashMap<String, T>()

    /**
     * 根据sessionId自动生成客户端的Adapter
     * 如果有，则是获取
     */
    override fun get(ssId: String): T
    {
        var adapter = cache[ssId]
        if (adapter == null)
        {
            adapter = klass.createInstance()
            cache[ssId] = adapter
        }
        return adapter
    }

    override fun has(ssId: String): Boolean
    {
        return cache.contains(ssId)
    }

    /**
     * 移除关系，大多数是因为客户端关闭了
     */
    override fun remove(ssId: String)
    {
        cache.remove(ssId)
    }
}